﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[ExecuteInEditMode]
[RequireComponent(typeof(LineRenderer))]
public class LightEffect : MonoBehaviour
{
    public float detail = 1;
    public float displacement = 15;
    public Transform endTran;
    public Transform startTran;

    private LineRenderer _renderer;
    private List<Vector3> _linePosList;

    public float yOffset;

    private void Awake()
    {
        _renderer = GetComponent<LineRenderer>();
        _linePosList = new List<Vector3>();
    }

    private void Update()
    {
        if (Time.timeScale != 0)
        {
            _linePosList.Clear();
            Vector3 startPos = Vector3.zero;
            Vector3 endPos = Vector3.zero;
            if (endTran != null)
            {
                endPos = endTran.position + Vector3.up * yOffset;
            }

            if (startTran != null)
            {
                startPos = startTran.position + Vector3.up * yOffset;
            }
            
            //获得开始点与结束点之间的随机生成点

            CollectLinPos(startPos,endPos, displacement);  

            _linePosList.Add(endPos);  

            //把点集合赋给LineRenderer

            _renderer.SetVertexCount(_linePosList.Count);  

            for (int i = 0, n = _linePosList.Count; i< n; i++)  

            {  

                _renderer.SetPosition(i, _linePosList[i]);  

            }  

        }  
        
    }
    
    
    //收集顶点，中点分形法插值抖动  

    private void CollectLinPos(Vector3 startPos,Vector3 destPos,float displace)  

    {  

        //递归结束的条件

        if (displace < detail)  

        {  

            _linePosList.Add(startPos);  

        }  

        else  

        {  

            float midX = (startPos.x + destPos.x) / 2;  

            float midY = (startPos.y + destPos.y) / 2;  

            float midZ = (startPos.z + destPos.z) / 2;  

            midX += (float)(UnityEngine.Random.value - 0.5) * displace;  

            midY += (float)(UnityEngine.Random.value - 0.5) * displace;  

            midZ += (float)(UnityEngine.Random.value - 0.5) * displace;  

            Vector3 midPos =new Vector3(midX,midY,midZ);  

            //递归获得点

            CollectLinPos(startPos,midPos, displace / 2);  

            CollectLinPos(midPos,destPos, displace / 2);  

        }  

    }
}
